//
//  SetBabyInfoViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/4.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "SetBabyInfoViewController.h"
#import "GenderViewController.h"
#import "HeightViewController.h"
#import "WeightViewController.h"
#import "DateViewController.h"
#import "GradeViewController.h"
#import "SyncManager.h"
#import "LeoMsg.h"
#import "MainPageViewController.h"
#import "GrowthViewController.h"
#import "LocationViewController.h"
#import "ManagerViewController.h"
#import "ChatListViewController.h"
#import <UIKit/UIKit.h>

#import "AppDelegate.h"

#import "SyncManager.h"
#import "DataManager.h"

@interface SetBabyInfoViewController ()
@property (nonatomic,strong) SyncManager *syncManager;
@property (nonatomic,strong) DataManager *dataManager;

@property(nonatomic,strong) NSString *photoUrl;
@property(nonatomic,strong) NSString *photoName;
@property(nonatomic,strong) NSString *saveUrl;
@property (nonatomic, strong) MAMapView *mapView;
@property(nonatomic,strong) UIActionSheet *actionSheet;
@property(nonatomic,strong) UIImagePickerController *picker;
@property(nonatomic,weak) AppDelegate *mydelegate;
@property(nonatomic,strong) NSString *phoneStr;
@end

@implementation SetBabyInfoViewController
@synthesize genderLabel;
@synthesize heightLabel;
@synthesize weightLabel;
@synthesize birthLabel;
@synthesize gradeLabel;
@synthesize genderView;
@synthesize heightView;
@synthesize weightView;
@synthesize birthView;
@synthesize gradeView;
@synthesize submitButton;
@synthesize syncManager;
@synthesize nameText;
@synthesize phoneLable;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [nameText resignFirstResponder];
}

-(void)dealloc
{
    syncManager=NULL;
    self.photoName=NULL;
    self.photoUrl=NULL;
    self.saveUrl=NULL;
    self.mapView=NULL;
    self.actionSheet.delegate=nil;
    self.actionSheet=NULL;
    self.picker.delegate=nil;
    self.picker=NULL;
    self.phoneStr=NULL;
}
- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
-(void)viewWillAppear:(BOOL)animated{
    self.hidesBottomBarWhenPushed = NO;
    
    UIColor *blueBackgroundColor=[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1];
    UIImage *blueBackgroundImage=[self imageWithColor:blueBackgroundColor];
    
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    // white.png图片自己下载个纯白色的色块，或者自己ps做一个
    [navigationBar setBackgroundImage:blueBackgroundImage
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage new]];
    
    [self.headView.layer setMasksToBounds:YES];
    self.headView.layer.cornerRadius=self.headView.bounds.size.width/2;
    self.headView.clipsToBounds=YES;
}

-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
-(void)getBabyData{
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    self.watch=watch;
    
    if (self.watch!=NULL)
    {
        if(watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"])
        {
            nameText.text=watch.nickname;
        }
        if (watch.gender==1){genderLabel.text=@"女孩";}else{genderLabel.text=@"男孩";};
        if(watch.height>0)
        {
            heightLabel.text=[NSString stringWithFormat:@"%0.0f",watch.height];
            heightLabel.text=[heightLabel.text stringByAppendingString:@"cm"];
        }
        if(watch.weight>0)
        {
            weightLabel.text=[NSString stringWithFormat:@"%0.0f",watch.weight];
            weightLabel.text=[weightLabel.text stringByAppendingString:@"kg"];
        }
        if(watch.birth!=NULL&&![watch.birth isEqualToString:@"(null)"]&&![watch.birth isEqualToString:@""])
        {
            birthLabel.text=watch.birth;
            NSLog(@"%@",watch.birth);
            birthLabel.text=[Tooler second2Stringformat:watch.birth withFormatter:@"yyyy-MM-dd"];
        }
        if(watch.className!=NULL&&![watch.className isEqualToString:@"(null)"])
        {
            if ([watch.className isEqual:@"0"]){gradeLabel.text=@"未上学";}
            if ([watch.className isEqual:@"1"]){gradeLabel.text=@"幼儿园小班";}
            if ([watch.className isEqual:@"2"]){gradeLabel.text=@"幼儿园中班";}
            if ([watch.className isEqual:@"3"]){gradeLabel.text=@"幼儿园大班";}
            if ([watch.className isEqual:@"4"]){gradeLabel.text=@"一年级";}
            if ([watch.className isEqual:@"5"]){gradeLabel.text=@"二年级";}
            if ([watch.className isEqual:@"6"]){gradeLabel.text=@"三年级";}
            if ([watch.className isEqual:@"7"]){gradeLabel.text=@"四年级";}
            if ([watch.className isEqual:@"8"]){gradeLabel.text=@"五年级";}
            if ([watch.className isEqual:@"9"]){gradeLabel.text=@"六年级";}
            if ([watch.className isEqual:@"10"]){gradeLabel.text=@"七年级";}
            if ([watch.className isEqual:@"11"]){gradeLabel.text=@"八年级";}
            if ([watch.className isEqual:@"12"]){gradeLabel.text=@"九年级";}
            if ([watch.className isEqual:@"13"]){gradeLabel.text=@"自定义";}
            
        }
        if(watch.pic_url!=NULL&&![watch.pic_url isEqualToString:@"(null)"]&&![watch.pic_url isEqualToString:@""])
        {
            self.headView.image=[UIImage imageNamed:[[Tooler getDocumentDirectory] stringByAppendingString:watch.pic_url]];
            self.photoUrl=[[Tooler getDocumentDirectory] stringByAppendingString:watch.pic_url];
            self.photoName=watch.photoName;
            self.saveUrl=watch.pic_url;
        }
        else
        {
            if(watch.gender==1)//女孩
            {
                self.headView.image=[UIImage imageNamed:@"avater_girl.png"];
            }
            else//男孩
            {
                self.headView.image=[UIImage imageNamed:@"avater_boy.png"];
            }
        }
        if(watch.sim!=NULL&&![watch.sim isEqualToString:@"(null)"]&&![watch.sim isEqualToString:@""])
        {
            phoneLable.text=watch.sim;
            self.phoneStr=watch.sim;
        }

    }
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameText.delegate=self;
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"儿童信息";
    [self initDataProxy];
    //defaul value
    //self.photoUrl=[[NSBundle mainBundle]  pathForResource:@"avater_boy" ofType:@"png"];
    //self.saveUrl=[[NSBundle mainBundle]  pathForResource:@"avater_boy" ofType:@"png"];
    //self.photoName=@"avater_boy.png";
    [self getBabyData];
    [self.headView.layer setMasksToBounds:YES];
    self.headView.layer.cornerRadius=self.headView.bounds.size.width/2;
    self.headView.clipsToBounds=YES;
    [self.indicatorView.layer setMasksToBounds:YES];
    self.indicatorView.layer.cornerRadius=5;
    if(self.mydelegate.isAdmin==YES)
    {
        [self initViewActions];
    }
    else
    {
        self.genderNext.hidden=YES;
        self.heightNext.hidden=YES;
        self.weightNext.hidden=YES;
        self.birthNext.hidden=YES;
        self.gradeNext.hidden=YES;
        self.submitButton.hidden=YES;
        self.submitButton.enabled=NO;
        self.nameText.enabled=NO;
        self.simNext.hidden=YES;
    }
    if(self.watch==NULL||self.watch.deviceUid==NULL)
    {
        NSLog(@"%@,viewDidLoad,watch is null.",setBaby_tag);
        //[LeoMsg showMsg:@"程序发生错误"];
        return;
    }
    // Do any additional setup after loading the view from its nib.
    self.actionSheet = [[UIActionSheet alloc]
                        initWithTitle:nil
                        delegate:self
                        cancelButtonTitle:nil
                        destructiveButtonTitle:nil
                        otherButtonTitles:@"拍照", @"从手机相册选择",@"取消",nil];
    self.actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    //设置选择后的图片可被编辑
    self.picker.allowsEditing = YES;
    //设置图片选择器样式
    self.picker.allowsEditing = YES;
    
    self.picker.navigationBar.translucent =NO;
    
    [self.picker.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.picker.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];

}

-(void)initViewActions{
    //add touch TapGestureRecognizer for views
    UITapGestureRecognizer *tapReconizerToGender = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(genderAction)];
    [self.genderView addGestureRecognizer:tapReconizerToGender];
    
    UITapGestureRecognizer *tapReconizerToHeight = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(heightAction)];
    [self.heightView addGestureRecognizer:tapReconizerToHeight];
    
    UITapGestureRecognizer *tapReconizerToWeight = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(weightAction)];
    [self.weightView addGestureRecognizer:tapReconizerToWeight];

    UITapGestureRecognizer *tapReconizerToBirth = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(BirthAction)];
    [self.birthView addGestureRecognizer:tapReconizerToBirth];
    
    UITapGestureRecognizer *tapReconizerToGrade = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(GradeAction)];
    [self.gradeView addGestureRecognizer:tapReconizerToGrade];
    
    UITapGestureRecognizer *tapReconizerToHead = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headAction)];
    [self.headView addGestureRecognizer:tapReconizerToHead];
    
    UITapGestureRecognizer *tapReconizerToSim = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setSim)];
    [self.simView addGestureRecognizer:tapReconizerToSim];
  
    [submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchDown];
}

-(void)submitAction
{
    //collect infomation then post to nw , if success , update local database
    if(self.nameText.text==NULL||[self.nameText.text length]<=0)
    {
        [LeoMsg showMsg:@"昵称不能为空"];
        return;
    }
    if ([Tooler checkStringIllegal:self.nameText.text ChnLength:6 EngLength:10]==1)
    {
        [LeoMsg showMsg:@"昵称不合法"];
        return;
    }
    if ([Tooler checkStringIllegal:self.nameText.text ChnLength:6 EngLength:10]==2)
    {
        [LeoMsg showMsg:@"昵称太长，中文字符只能输入6个，英文字符最多10个"];
        return;
    }
    if(self.phoneStr==NULL||[self.phoneStr length]<=0)
    {
        [LeoMsg showMsg:@"手机号码不能为空"];
        return;
    }
    if([self.phoneStr length]!=11)
    {
        [LeoMsg showMsg:@"输入的手机号码无效，请输入正确的手机号码"];
        return;
    }
    syncManager=[[SyncManager alloc] init];
    if(syncManager==NULL)
    {
        NSLog(@"SetBabyInfoViewController:submitAction,syncManager is null.");
        [LeoMsg showMsg:@"程序发生错误，code is 44"];
        return;
    }
    self.indicatorView.hidden=NO;
    self.indicator.hidden=NO;
    [self.indicator startAnimating];
    self.watch.nickname=self.nameText.text;
    self.watch.height=[self.heightLabel.text floatValue];
    self.watch.weight=[self.weightLabel.text floatValue];
    self.watch.age=10;
    if(self.birthLabel.text!=NULL&&self.birthLabel.text.length>0)
    {
        self.watch.birth=self.birthLabel.text;
        NSString *birth=[NSString stringWithFormat:@"%@ 00:00:00",self.watch.birth];
        NSString *birthStamp=[Tooler strToLocalTime:birth];
        self.watch.birth=birthStamp;
    }
    self.watch.className=[NSString stringWithFormat:@"%d",[Tooler getGradeNumber:self.gradeLabel.text]];//self.gradeLabel.text;
    if([self.genderLabel.text isEqualToString:@"男孩"])
    {
        self.watch.gender=0;
    }
    else
    {
        self.watch.gender=1;
    }
    self.watch.is_active=1;
    self.watch.pic_url=self.photoUrl;
    self.watch.photoName=self.photoName;
    self.watch.saveUrl=self.saveUrl;
    if(self.phoneStr!=NULL)
        self.watch.sim=self.phoneStr;
    [syncManager setWatchInfo:self.watch completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            self.indicatorView.hidden=YES;
            self.indicator.hidden=YES;
            [self.indicator stopAnimating];
            if(self.type==2)//管理模块修改宝宝信息
            {
                [LeoMsg showMsg:@"宝宝信息修改成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEBABYINFO object:nil  userInfo:nil];
                [self.navigationController popViewControllerAnimated:YES];
                return ;
            }
            //if(self.mydelegate.addWatchMethod==1)//通过手表列表添加手表
            //{
             //   [self.navigationController popToRootViewControllerAnimated:YES];
             //   self.mydelegate.addWatchMethod=0;
            //}
            //else//注册绑定账号
            //{
                //跳到主界面
                NSMutableArray *items = [[NSMutableArray alloc]init];
                CGRect rect = [UIScreen mainScreen].bounds;
                self.mydelegate.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 20+44, rect.size.width, rect.size.height-(20+44))];
                BaseMapViewController *locationViewController = [[LocationViewController alloc]init];
                locationViewController.mapView=self.mydelegate.mapView;
                self.mydelegate.search = [[AMapSearchAPI alloc] init];
                [items addObject:locationViewController];
                
                ChatListViewController *chatViewController = [[ChatListViewController alloc]init];
                [items addObject:chatViewController];
                
                
                GrowthViewController *growthViewController = [[GrowthViewController alloc]init];
                [items addObject:growthViewController];
                
                ManagerViewController *managerViewController = [[ManagerViewController alloc]init];
                [items addObject:managerViewController];
                
                
                MainPageViewController *mainPageViewController = [[MainPageViewController alloc]init];
                [mainPageViewController setViewControllers:items];
                
                UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:mainPageViewController];
               if(self.mydelegate!=NULL)
                   [self.mydelegate setNavProperty:nav];
                mainPageViewController.extendedLayoutIncludesOpaqueBars = YES;
                managerViewController.motherTabViewController=mainPageViewController;
                locationViewController.motherTabViewController=mainPageViewController;
                growthViewController.motherTabViewController=mainPageViewController;
                self.view.window.rootViewController=nav;
                [self.navigationController popToRootViewControllerAnimated:YES];
            //}
          
        }
        else
        {
            self.indicatorView.hidden=YES;
            self.indicator.hidden=YES;
            [self.indicator stopAnimating];
            [Tooler showHttpMsg:result description:description msg:@"宝宝信息修改失败"];
        }
    }];
}
- (void)setSim {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"请输入宝宝手机号码"
                                                    message:nil
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    // 基本输入框，显示实际输入的内容
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    //设置输入框的键盘类型
    UITextField *nickTextField = [alert textFieldAtIndex:0];
    nickTextField.text=self.phoneStr;
    nickTextField.keyboardType = UIKeyboardTypeNumberPad;
    [nickTextField addTarget:self action:@selector(phoneTextFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [alert show];
    alert=NULL;
    
}
- (void)phoneTextFieldChange:(UITextField *)textField
{
    if (textField.text.length > 20) {
        textField.text = [textField.text substringToIndex:20];
    }
    textField.text=[Tooler validateNumber:textField.text];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
        return;
    // 取得输入的值
    UITextField *nickTextField = [alertView textFieldAtIndex:0];
    NSString* simStr = [nickTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([simStr isEqualToString:@""]||[simStr length]<=0)
    {
        [LeoMsg showMsg:@"手机号码不能为空"];
        return;
    }
    else if([simStr length]!=11||[Tooler checkStringBegin:simStr]==NO)
    {
        [LeoMsg showMsg:@"手机号码无效，请输入正确的手机号码"];
        return;
    }
    else
    {
        phoneLable.text=simStr;
        self.phoneStr=simStr;
        simStr=NULL;
    }
}

- (IBAction)setHead:(id)sender {
    [self headAction];
}

-(void)headAction
{
    [self.nameText resignFirstResponder];
    [self.actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self camera];
    }else if (buttonIndex == 1) {
        [self LocalPhoto];
        
    }else if(buttonIndex == 2) {
        
    }
    
}
-(void)camera
{
    self.picker.sourceType=UIImagePickerControllerSourceTypeCamera;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)LocalPhoto
{
   
    self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [self dismissViewControllerAnimated:YES completion:nil];

}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data = UIImageJPEGRepresentation(image, 0.3);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
        if([Tooler isDirectoryExist:DocumentsPath])
        {
            NSString *ts=[Tooler getTS];
            self.saveUrl=[NSString stringWithFormat:@"/headimg/image%@.jpg",ts];
            //得到选择后沙盒中图片的完整路径
            self.photoUrl = [[NSString alloc]initWithFormat:@"%@/image%@.jpg",DocumentsPath,ts];
            self.photoName=[NSString stringWithFormat:@"image%@.jpg",ts];
            NSError *error;
            [data writeToFile:self.photoUrl options:NSDataWritingFileProtectionComplete error:&error];
            if(error==NULL)
            {
                self.headView.image=[UIImage imageNamed:self.photoUrl];
            }
            
        }
        [self.picker dismissViewControllerAnimated:YES completion:nil];
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

        
    }
    
}

-(void)genderAction
{
    [self.nameText resignFirstResponder];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    

    NSString *transferData=NULL;
    if (self.genderLabel.text!=NULL)
    {
        if ([self.genderLabel.text isEqualToString:@"女孩"])
        {
            transferData=@"女孩";
        }
        else
        {
            transferData=@"男孩";
        }
    }

    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    GenderViewController *gender=[[GenderViewController alloc]init];
    //
    [gender setMotherWindow:alertView];
    [gender setMotherLabel:genderLabel];
    gender.originalGender=transferData;
    if(self.photoUrl==NULL)
    {
        [gender setMotherImg:self.headView];
    }
    else
    {
        [gender setMotherImg:NULL];
    }
    alertView.rootViewController=gender;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

-(void)heightAction
{
    [self.nameText resignFirstResponder];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    

    NSString *transferData=NULL;
    if (self.heightLabel.text!=NULL)
    {
        transferData=self.heightLabel.text;
    }

    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    HeightViewController *heightViewController=[[HeightViewController alloc]init];
    //
    [heightViewController setMotherWindow:alertView];
    [heightViewController setMotherLabel:heightLabel];
    heightViewController.originalHeightString=transferData;
    alertView.rootViewController=heightViewController;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

-(void)weightAction
{
    [self.nameText resignFirstResponder];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    

    NSString *transferData=NULL;
    if (self.weightLabel.text!=NULL)
    {
        transferData=self.weightLabel.text;
    }
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    WeightViewController *weightViewController=[[WeightViewController alloc]init];
    //
    [weightViewController setMotherWindow:alertView];
    [weightViewController setMotherLabel:weightLabel];
    
    alertView.rootViewController=weightViewController;
    weightViewController.originalRoundString=transferData;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

-(void)BirthAction
{
    [self.nameText resignFirstResponder];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    

    NSString *transferData=NULL;
    if (self.birthLabel.text!=NULL)
    {
        transferData=self.birthLabel.text;
    }

    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    DateViewController *date=[[DateViewController alloc]init];
    //
    [date setMotherWindow:alertView];
    [date setMotherLabel:birthLabel];
    date.originalBirth=transferData;
    alertView.rootViewController=date;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

-(void)GradeAction
{
    [self.nameText resignFirstResponder];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    

    NSString *transferData=NULL;
    if (self.gradeLabel.text!=NULL)
    {
        transferData=self.gradeLabel.text;
    }

    
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    GradeViewController *grade=[[GradeViewController alloc]init];
    //
    [grade setMotherWindow:alertView];
    [grade setMotherLabel:gradeLabel];
    grade.originalGrade=transferData;
    alertView.rootViewController=grade;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)tapBackGround:(id)sender {
    [self.nameText resignFirstResponder];
}
-(void)showErrorMsg:(NSString *)msg
{
    
}

- (IBAction)nameTextFieldChange:(id)sender {
    if(self.nameText.text.length>20)
        self.nameText.text=[self.nameText.text substringToIndex:20];
}



@end
